package com.sentiment.servlet;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.bson.Document;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sentiment.bean.OperationInfo;
import com.sentiment.bean.UserList;
import com.sentiment.database.bean.Role;
import com.sentiment.database.bean.User;
import com.sentiment.database.bean.UserInfo;
import com.sentiment.database.bean.User_Roles;
import com.sentiment.database.dbUtil.DbUtil;
import com.sentiment.shiro.ActiveUser;
import com.sentiment.tools.Format;
import com.sentiment.tools.Paging;


/**
 * Servlet implementation class GetUserInfo
 */
@WebServlet("/UserInfoServlet")
public class UserInfoServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
  
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
	
		doPost(request, response);
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
	
		String methodName = request.getParameter("method");
		try{
			Method method = getClass().getMethod(methodName, 
					HttpServletRequest.class, HttpServletResponse.class);
			method.invoke(this, request, response);
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	/**
	 * 得到用户列表
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void GetUserList(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		
		List<UserList> users = new ArrayList<>();
		//连接数据库获取用户信息
		UserList user = new UserList();
		int page  = Integer.parseInt(request.getParameter("pagenum"));
		users = user.getUserList(page, 10);		
		long count = user.getCount();
		
		ObjectMapper mapper = new ObjectMapper();
		String jsonArray = mapper.writeValueAsString(users);				
		String jsonStr = "{\"recordsTotal\":"+ count +",\"users\":" + jsonArray+"}";

		System.out.println(jsonStr);
		
		response.setCharacterEncoding("UTF-8");
		response.getWriter().print(jsonStr);
		
	}
	
	/**
	 * 查看用户个人信息
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void  GetUserInfo(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		
		String user_id = request.getParameter("user_id");
		System.out.println(user_id);
		
		if(user_id.equals("myself")){
			Subject subject = SecurityUtils.getSubject();
			ActiveUser activeUser = (ActiveUser) subject.getPrincipal();
			if(activeUser == null){
				user_id = null;
			}else{
				user_id = activeUser.getUser_id();
			}
		}
		
		String jsonStr = "";
		if(user_id == null){
			jsonStr = "{\"Info\":" + "\"" + OperationInfo.LoginTimeOut + "\"" +"}";
		}else{
			UserInfo info = new UserInfo();
			info = info.getUserInfoByUser_id(user_id);
		
			ObjectMapper mapper = new ObjectMapper();
			String jsonArray = mapper.writeValueAsString(info);
			
			jsonStr = "{\"userinfo\":" + jsonArray+"}";
		}
		System.out.println(jsonStr);
		response.setCharacterEncoding("UTF-8");
		response.getWriter().print(jsonStr);
		
	}
	
	/**
	 * 更改用户状态
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void ChangeUserStatus(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {

		String user_id = request.getParameter("user_id");
		String now_status = request.getParameter("now_status");
		
		System.out.println(user_id);
		System.out.println(now_status);
		
		String operStr = "";
		
		User user = new User();
		user = user.getUserByUser_id(user_id);
		if(user == null){
			operStr = OperationInfo.UserNotFind;
		}else{
		
			if(now_status.equals("false")){
				operStr = user.Locked();
			}else if(now_status.equals("true")){
				operStr = user.UnLocked();
			}else{
				operStr = OperationInfo.OperNotDefine;
			}
		}
		
		response.setCharacterEncoding("UTF-8");
		response.getWriter().print(operStr);
	}
	
	/**
	 * 更改用户密码
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void ChangeUserPassword(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		String oldpassword = request.getParameter("oldpaswd");
		String newpassword = request.getParameter("newpassword");
		
		Subject subject = SecurityUtils.getSubject();
		ActiveUser activeUser = (ActiveUser) subject.getPrincipal();
		String user_id = activeUser.getUser_id();
		
		User user = new User();
		user = user.getUserByUser_id(user_id);
		
		String salt =user.getSalt();
		//散列次数
		int hashIterations = 1;
		Md5Hash md5Hash = new Md5Hash(oldpassword, salt, hashIterations);
		String info = "";
		String password_md5 =  md5Hash.toString();
		
		if(!password_md5.equals(user.getPassword())){
			//用户输入原密码不正确
			info = OperationInfo.OldPasswordErr;
		}else{
			info = user.ChargePassword(newpassword);
		}
		
		response.setCharacterEncoding("UTF-8");
		response.getWriter().print(info);
	}
	
	/**
	 * 根据用户信息查找用户
	 * 存在该用户则返回用户信息   
	 * 否则返回提示信息  
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void Query(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		
		request.setCharacterEncoding("UTF-8");
		String usercode = request.getParameter("username");		
		String registered_date = request.getParameter("registered_date");
		String statusStr = request.getParameter("status");
		String role_detail = request.getParameter("role");
		int page  = Integer.parseInt(request.getParameter("pagenum"));
		
		DbUtil db = new DbUtil();
		String info = "";
		List<Document> tlistuser = new ArrayList<>();
		
		//User 表，查询条件中 usercode 与 status 其中一个不为空时查询
		List<String> listbyuserid = new ArrayList<>();
		List<String> keylist = new ArrayList<>();
		Boolean status = false;
		if(!usercode.equals("")){
			keylist.add("usercode");
		}
		if(!statusStr.equals("")){
			keylist.add("status");
			if(statusStr.equals("true")){
				status = true;
			}
		}
		if(keylist.size() != 0){
			String []keys = keylist.toArray(new String [keylist.size()]);
			User user = new User(null, usercode, null, null, status);
			
			db.openConnection(User.dbName, User.collection);
			tlistuser = db.queryMany(user.toDocument(), keys);
			db.closeConnection();
			if(tlistuser.size() == 0){
				info = OperationInfo.NoSuchUser;
			}else{
				for (int i = 0; i < tlistuser.size(); i++) {
					user = new User(tlistuser.get(i));
					listbyuserid.add(user.get_id());
				}
			}
		}
		
		//UserInfo 表 , 查询条件中注册时间不为空,且没有查找对象为空的信息时查找
		List<String> listbyuserinfoid = new ArrayList<>();
		if(info.equals("") && !registered_date.equals("")){			
			UserInfo userinfo = new UserInfo();
			userinfo.setRigisterdate(Format.ToDBStrDate(registered_date));			
			db.openConnection(UserInfo.dbName, UserInfo.collection);
			tlistuser = db.queryMany(userinfo.toDocument(), new String[]{"rigisterdate"});
			db.closeConnection();
			if(tlistuser.size() == 0){
				info = OperationInfo.NoSuchUser;
			}else{
				for (int i = 0; i < tlistuser.size(); i++) {
					userinfo = new UserInfo(tlistuser.get(i));
					listbyuserinfoid.add(userinfo.getUser_id());
				}
			}
		}
		
		//User_Roles 表,查询条件中角色不为空，且没有查找为空的信息时查找
		List<String> listbyuser_rolesid = new ArrayList<>();
		if(info.equals("") && !role_detail.equals("")){
			
			Role role = new Role();
			role = role.getRoleByRole_detail(role_detail);
			if(role == null){
				info = OperationInfo.NoSuchUser;
			}else{
				db.openConnection(User_Roles.dbName, User_Roles.collection);
				tlistuser = db.queryByOneinList("roles_id", role.get_id());
				db.closeConnection();
				if(tlistuser.size() == 0){
					info = OperationInfo.NoSuchUser;
				}else{
					for (int i = 0; i < tlistuser.size(); i++) {
						User_Roles user_roles = new User_Roles(tlistuser.get(i));
						listbyuser_rolesid.add(user_roles.getUser_id());
					}
				}
			}
		}
		
		//合并结果
		String jsonStr = "";
		List<String> userid = new ArrayList<>();
		if(info.equals("")){
			if(listbyuserid.size() != 0){
				if(listbyuserinfoid.size() != 0){
					listbyuserid.retainAll(listbyuserinfoid);
				}
				if(listbyuser_rolesid.size() != 0){
					listbyuserid.retainAll(listbyuser_rolesid);
				}
				userid = listbyuserid;
			}else if(listbyuserinfoid.size() != 0){
				if(listbyuser_rolesid.size() != 0){
					listbyuserinfoid.retainAll(listbyuser_rolesid);
				}
				userid = listbyuserinfoid;
			}else if(listbyuser_rolesid.size() != 0){
				userid = listbyuser_rolesid;
			}else{
				jsonStr = "{\"recordsTotal\":"+ 0 +",\"Info\":" + "\"" +OperationInfo.NoSuchUser + "\"" +"}";
			}
			
			if(userid.size() == 0){
				jsonStr = "{\"recordsTotal\":"+ 0 +",\"Info\":" + "\"" +OperationInfo.NoSuchUser + "\"" +"}";
			}else{
				List<UserList> listuserlist = new ArrayList<>();
				long count = userid.size();
				userid = Paging.pagingStr(userid, page, 10);
				for (int i = 0; i < userid.size(); i++) {
					User user = new User();
					user = user.getUserByUser_id(userid.get(i));
					UserList userlist = new UserList();
					userlist = userlist.getUserListByUser(user);
					listuserlist.add(userlist);
				}
				ObjectMapper mapper = new ObjectMapper();
				String jsonArr = mapper.writeValueAsString(listuserlist);
				jsonStr = "{\"recordsTotal\":"+ count +",\"users\":" + jsonArr+"}";
				
			}
			
		}else{
			jsonStr = "{\"recordsTotal\":"+ 0 +",\"Info\":" + "\"" + info + "\"" +"}";
		}	
		
		System.out.println(jsonStr);
		response.setCharacterEncoding("UTF-8");
		response.getWriter().print(jsonStr);
		
	}

}
